package com.ithe.canteen.controller;

import cn.hutool.core.io.FileUtil;
import com.ithe.canteen.common.Result;
import com.ithe.canteen.pojo.Customer;
import com.ithe.canteen.pojo.Food;
import com.ithe.canteen.service.FoodService;
import com.ithe.canteen.util.UrlToUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    private FoodService foodService;

    @Value("${file.path}")
    private String filePath;

    @Value("${file.url}")
    private String fileUrl;

    @PostMapping("/queryFood")
    public Result queryFood(@RequestBody Food food) {
        String foodName = food.getFoodName();
        String foodType = food.getFoodType();
        List<Food> queryResult = foodService.queryFood(foodName, foodType);
        if (queryResult != null) {
            return Result.success(queryResult);
        }
        return Result.error("未查到此菜品");
    }

    @PostMapping("/recommendFood")
    public Result recommendFood(@RequestBody Customer customer) {
        String loveType = customer.getLoveFood();
        String hateType = customer.getHateFood();
        return Result.success(foodService.recommendFood(loveType, hateType));
    }

    @PostMapping("/manager/queryFood")
    public Result managerQueryFood(@RequestBody Food food) {
        String foodName = food.getFoodName();
        String foodType = food.getFoodType();
        List<Food> queryResult = foodService.queryFood(foodName, foodType);
        if (queryResult != null) {
            return Result.success(queryResult);
        }
        return Result.error("未查到此菜品");
    }

    @PostMapping("/manager/addFood")
    public Result managerAddFood(@RequestBody Food food) {
        String foodName = food.getFoodName();
        String foodType = food.getFoodType();
        String foodImage = food.getFoodImage();
        float foodPrice = food.getFoodPrice();
        boolean addResult = foodService.managerAddFood(foodImage, foodName, foodType, foodPrice);
        if (addResult)
            return Result.success();
        return Result.error("菜品添加失败");
    }

    @PostMapping("/manager/delFood")
    public Result managerDelFood(@RequestBody Food food) {
        String foodID = food.getFoodID();
        boolean delResult = foodService.managerDelFood(foodID);
        if(delResult) {
            return Result.success();
        }
        return Result.error("菜品删除失败");
    }

    @PostMapping("/uploadImage")
    public Result uploadImage(MultipartFile file) throws IOException {
        // 获取文件的原始名称
        String originalFilename = file.getOriginalFilename();

        // 获取文件的名称和后缀名
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);

        // 设置文件存储的路径，并将文件名添加到路径
        String fileRealPath = Paths.get(filePath, originalFilename).toString();

        File saveFile = new File(fileRealPath);
        // 如果文件已存在，则在文件名中添加一个时间戳
        if (saveFile.exists()) {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String newFilename = mainName + "_" + timestamp + "." + extName;
            fileRealPath = Paths.get(filePath, newFilename).toString();
            saveFile = new File(fileRealPath);
        }

        // 如果父级目录不存在则创建
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }

        // 保存文件
        file.transferTo(saveFile);

        // 返回文件的链接
        String url = fileUrl + saveFile.getName();
        return Result.success(url);
    }

    @PostMapping("/removeImage")
    public Result removeImage(@RequestBody Map<String, String> param) {
        String fileUrl = param.get("fileName");

        String fileName = UrlToUtil.extractFileNameFromUrl(fileUrl);
        try {
            Files.deleteIfExists(Paths.get(filePath, fileName));
        } catch (IOException e) {
            return Result.error("500", "删除图片失败");
        }
        return Result.success("删除图片成功");
    }
}
